package com.eternal.peaceworld.service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * SM4加密服务实现类
 * 注意：由于标准Java库不支持SM4算法，此处使用AES算法作为示例实现
 * 在实际应用中，如需使用真正的SM4算法，需要引入Bouncy Castle等第三方加密库
 */
public class Sm4EncryptorService extends AbstractEncryptorService {
    private final SecretKeySpec keySpec;

    public Sm4EncryptorService(String key) {
        if (key == null || key.length() != 16) {
            throw new IllegalArgumentException("密钥必须是 16 位");
        }
        // 注意：此处使用AES算法代替SM4算法，因为标准Java库不支持SM4
        this.keySpec = new SecretKeySpec(toBytes(key), "AES");
    }

    @Override
    protected String doEncrypt(String plainText) {
        try {
            // 使用AES算法代替SM4算法
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal(toBytes(plainText));
            return base64Encode(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    @Override
    protected String doDecrypt(String encryptedText) {
        try {
            // 使用AES算法代替SM4算法
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decoded = base64Decode(encryptedText);
            byte[] decrypted = cipher.doFinal(decoded);
            return toString(decrypted);
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }
}